package algorithm.swordoff;

import java.util.Arrays;

/**
 * 顺时针打印矩阵
 */

public class SQ29 {

    public int[] spiralOrder(int[][] matrix) {
        if(matrix.length == 0) return new int[0];

        int[] ans = new int[matrix.length * matrix[0].length];
        int up = 0, down = matrix.length-1, left = 0, right = matrix[0].length-1, index = 0;
        while (true) {
            // 先从左至右打印,打印后准备下一次左至右(即up+1),打印结束后若up<=down即可下次打印,因为进入时up这一行还没打印,所以要带等号,下同
            for (int i = left; i <= right; i++) ans[index++] = matrix[up][i];
            if (++up > down) break;

            // 从上到下打印,打印后准备下一次上到下(即right-1),打印结束后若right>=left即可下次打印
            for (int i = up; i <= down; i++) ans[index++] = matrix[i][right];
            if (--right < left) break;

            // 从右到左打印,打印后准备下一次右到左(即down+1),打印结束后若up<=down即可下次打印
            for (int i = right; i >= left; i--) ans[index++] = matrix[down][i];
            if (up > --down) break;

            // 从下到上打印,打印后准备下一次上到下(即left+1),打印结束后若right>=left即可下次打印
            for (int i = down; i >= up; i--) ans[index++] = matrix[i][left];
            if (right < ++left) break;
        }
        return ans;

    }

    public static void main(String[] args) {
        int[][] ints = {{1,2,3},{4,5,6},{7,8,9}};
        SQ29 sq29 = new SQ29();
        System.out.println(Arrays.toString(sq29.spiralOrder(ints)));
    }

}
